package com.nineclock.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Date;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SmsService smsService;

    @Override
    public SysUserDTO queryUser(String username) {

        // 查询用户名或手机号等于username 且 已激活的用户
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username)
                .or()
                .eq(SysUser::getMobile, username);
        wrapper.eq(SysUser::getStatus, 1);


        SysUser sysUser = userMapper.selectOne(wrapper);

        if(sysUser != null){
            SysUserDTO userDTO = BeanHelper.copyProperties(sysUser, SysUserDTO.class);
            return userDTO;
        }

        return null;
    }
    /**
     * 注册*/
    @Override
    public void register(SysRegisterDTO sysRegisterDTO) {
        //校验参数
        if(sysRegisterDTO == null || StringUtils.isEmpty(sysRegisterDTO.getMobile()) || StringUtils.isEmpty(sysRegisterDTO.getPassword()) || StringUtils.isEmpty(sysRegisterDTO.getCheckcode())){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);//无效请求参数
        }
        //校验验证码
        Boolean verifyResult = smsService.verifyCode(sysRegisterDTO.getMobile(),sysRegisterDTO.getCheckcode(),SMSConstant.SMS_TYPE_REGISTER);
        if(!verifyResult){
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }
        //新增用户
        SysUser sysUser = new SysUser();
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysRegisterDTO.getPassword()));
        sysUser.setMobile(sysRegisterDTO.getMobile());
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUser.setStatus((short) 1);

         userMapper.insert(sysUser);
    }


}
